//
//  ST_ShareAppView.swift
//  btvideo
//
//  Created by mac on 2020/7/14.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyJSON
import SwiftyUserDefaults
import SDWebImage

enum ST_SharePlatformType:Int {
    case subTypeWechatTimeline,subTypeWechatSession,subTypeQZone,subTypeQQFriend
}


struct ST_ShareViewStruct {
    let url:String
    let icon:String
    let title:String
    let content:String
}

class ST_ShareAppView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        self.cornerRadius = 16
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(22)
        }
        
        self.addSubview(shieldView)
        shieldView.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15/375.0*ScreenWidth)
            make.right.equalToSuperview().offset(-15/375.0*ScreenWidth)
            make.height.equalTo(70)
            make.centerX.equalToSuperview()
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
        }
        
        let offset = 37/2.0/375.0*ScreenWidth - 8
        
        self.addSubview(wechat_btn)
        wechat_btn.snp.makeConstraints { (make) in
            make.width.equalTo(70)
            make.height.equalTo(54+8+20)
            make.right.equalTo(self.snp.centerX).offset(-offset)
            make.top.equalTo(shieldView.snp.bottom).offset(30)
        }
        
        
        self.addSubview(qzone_btn)
        qzone_btn.snp.makeConstraints { (make) in
            make.top.width.height.equalTo(wechat_btn)
            make.left.equalTo(self.snp.centerX).offset(offset)
        }
        
        
        self.addSubview(wechat_moment_btn)
        wechat_moment_btn.snp.makeConstraints { (make) in
            make.top.width.height.equalTo(wechat_btn)
            make.right.equalTo(wechat_btn.snp.left).offset(-2*offset)
        }
        
        self.addSubview(q_q_btn)
        q_q_btn.snp.makeConstraints { (make) in
            make.top.width.height.equalTo(wechat_btn)
            make.left.equalTo(qzone_btn.snp.right).offset(2*offset)
        }
        
        self.addSubview(cancel_btn)
        cancel_btn.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.width.equalTo(80)
            make.height.equalTo(44)
            make.top.equalTo(q_q_btn.snp.bottom).offset(30)
        }
    }
    
    var share_data:ST_ShareViewStruct?
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel()
        
        let attrString = NSMutableAttributedString(string: "分享")
        
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        control.attributedText = attrString
        
        return control
    }()
    
    fileprivate lazy var shieldView:ST_SharePrivacyTipsView = {
       let control = ST_SharePrivacyTipsView()
        control.cornerRadius = 10
        return control
    }()
    
    fileprivate let baseTag = 1022
    
    fileprivate let shareTypeArray:[ST_SharePlatformType] = [ST_SharePlatformType.subTypeWechatTimeline,ST_SharePlatformType.subTypeWechatSession,ST_SharePlatformType.subTypeQZone,ST_SharePlatformType.subTypeQQFriend]
    
    fileprivate lazy var wechat_btn:ST_VerticalButton = {
       
        let control = ST_VerticalButton()
        control.tag = self.baseTag + 1
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 8, bottom: 8+20, right: 8)
        
        control.title_bottom_offset = 0
        
        control.setImageForAllStates(ST_ImageUtils.imageName("share_icon_Wechat")!)
        
        let attrString = NSMutableAttributedString(string: "微信好友")
      
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.38, green: 0.4, blue: 0.43, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        control.setTitle(attrString, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(share_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var wechat_moment_btn:ST_VerticalButton = {
       
        let control = ST_VerticalButton()
        control.tag = self.baseTag
        control.setImageForAllStates(ST_ImageUtils.imageName("share_icon_WechatMoment")!)
        
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 8, bottom: 8+20, right: 8)
        
        control.title_bottom_offset = 0
        
        let attrString = NSMutableAttributedString(string: "微信朋友圈")
      
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.38, green: 0.4, blue: 0.43, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        control.setTitle(attrString, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(share_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var qzone_btn:ST_VerticalButton = {
       
        let control = ST_VerticalButton()
        
        control.setImageForAllStates(ST_ImageUtils.imageName("share_icon_QZOne")!)
        
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 8, bottom: 8+20, right: 8)
        
        control.title_bottom_offset = 0
        control.tag = self.baseTag + 2
        let attrString = NSMutableAttributedString(string: "QQ空间")
      
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.38, green: 0.4, blue: 0.43, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        control.setTitle(attrString, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(share_handle(sender:)), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var q_q_btn:ST_VerticalButton = {
       
        let control = ST_VerticalButton()
        
        control.setImageForAllStates(ST_ImageUtils.imageName("share_icon_QQ")!)
        
        control.image_view_edges = UIEdgeInsets.init(top: 0, left: 8, bottom: 8+20, right: 8)
        
        control.title_bottom_offset = 0
        control.tag = self.baseTag + 3
        let attrString = NSMutableAttributedString(string: "QQ好友")
      
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.38, green: 0.4, blue: 0.43, alpha: 1)]
        
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        control.setTitle(attrString, for: UIControl.State.normal)
        
        control.addTarget(self, action: #selector(share_handle(sender:)), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    

    fileprivate lazy var cancel_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = UIColor.init(hex: 0xDFE3E9)
        control.cornerRadius = 44/2.0
        control.setTitleForAllStates("取消")
        control.setTitleColor(UIColor.white, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(cancel_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
}

extension ST_ShareAppView{
    
    @objc fileprivate func cancel_handle(){
        
        self.parentViewController?.goback_previous_controller()
        
    }
    
    @objc fileprivate func share_handle(sender:ST_VerticalButton){
        
        
        
        let tag = sender.tag - self.baseTag
        
        guard let type = self.shareTypeArray[safe:tag],let share = self.share_data else{
            return
        }
        
        
        
        let str = share.url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
        
        
        guard let url = str?.url else{
            return
        }
        
        NotificationCenter.default.post(name: .onClickShareMyApp, object: nil)
        
        SCComponets.alert_dispatcher?.request_award_sync()
        
        if type == ST_SharePlatformType.subTypeQQFriend || type == ST_SharePlatformType.subTypeQZone{
            
            let news = QQApiNewsObject.init(url: url, title: share.title, description: share.content, previewImageURL: share.icon.url, targetContentType: QQApiURLTargetType.news)
            
            
            let req = SendMessageToQQReq.init(content: news)
            
            
            if type == ST_SharePlatformType.subTypeQZone{
                
                QQApiInterface.sendReq(toQZone: req)
                
            }else{
                
                QQApiInterface.send(req)
                
            }
        }else{
            
            
            SDWebImageManager.shared.loadImage(with: share.icon.url, options: SDWebImageOptions(), progress: nil) { (image, d, e, t, f, url) in
                
                if let img = image{
                    
                    let webpageObject = WXWebpageObject()
                    webpageObject.webpageUrl = str ?? ""
                    let message = WXMediaMessage()
                    message.title = share.title
                    message.description = share.content
                    message.setThumbImage(img)
                    
                    message.mediaObject = webpageObject;
                 
                    let req = SendMessageToWXReq()
                    
                    req.bText = false
                    req.message = message
                    
                    if type == ST_SharePlatformType.subTypeWechatTimeline{
                        req.scene = Int32(WXSceneTimeline.rawValue)
                    }
                    
                    WXApi.send(req) { (f) in
                        
                        print("发送微信消息 ：",f)
                        
                    }
                }
                
            }
            
            
            
            
            
        }
        
        
        
        /*
        dict.ssdkSetupShareParams(byText: shareJson["content"].stringValue, images: shareJson["icon"].stringValue, url: url, title: shareJson["title"].stringValue, type: SSDKContentType.webPage)
        
        ShareSDK.share(type, parameters: dict) { (status, info, entity, err) in
            
            
            self.cancel_handle()
        }*/
        
    }
}


//MARK: - Share Tip
fileprivate class ST_SharePrivacyTipsView:UIView{

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.init(hex: 0x42CEDA, transparency: 0.1)
        
        self.addSubview(shieldImageView)
        shieldImageView.snp.makeConstraints { (make) in
            make.width.height.equalTo(35)
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(10)
        }
        
//        shieldImageView.backgroundColor = .random
        
        self.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalToSuperview().offset(55)
            make.right.equalToSuperview().offset(-2)
        }
        
//        titleLabel.backgroundColor = .random
        
        let str = NSMutableAttributedString.init(string: "请放心分享！伴心把你的隐私保护的超好~\n通过你分享的注册的人不会在伴心找到你的！")
        
        let paragrap = NSParagraphStyle.create_line_spacing_paragraph_style(lineSpacing: 6)
        
        str.addAttributes([NSAttributedString.Key.foregroundColor:UIColor.init(hex: 0x42CEDA)!,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),.paragraphStyle:paragrap], range: NSRange.init(location: 0, length: str.length))
        
        titleLabel.attributedText = str
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    fileprivate lazy var shieldImageView:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("privacy_shield"))
          return control
      }()

    fileprivate lazy var titleLabel:UILabel = {
      let control = UILabel()
        control.numberOfLines = 0
        return control
    }()
}

